package com.wh.util.security;

import java.security.MessageDigest;
import java.security.Provider;

import com.wh.lang.LogUtil;

public class MD5 {
	static Provider provider = new sun.security.provider.Sun();

	private MD5() {}

	public static String encrypt(String str) {
		return encrypt(str, true);
	}

	public static String encrypt(String str, boolean sensitiveCase) {
		if (str == null) str = "";
		if (!sensitiveCase) str = str.toUpperCase();
		return _encrypt(str);
	}

	private static String _encrypt(String str) {
		String digest = "";
		try {
			MessageDigest currentAlgorithm = MessageDigest.getInstance("md5", provider);
			digest = MD5.convert(str, currentAlgorithm);
		} catch (Throwable e) {
			if (LogUtil.rootLog.isErrorEnabled()) LogUtil.rootLog.error("生成MD5出错", e);
		}
		return digest;
	}

	private static String convert(String str, MessageDigest digest) {
		StringBuilder convertBud = new StringBuilder();
		digest.reset();
		byte[] mess = str.getBytes();
		byte[] hash = digest.digest(mess);
		for (int i = 0; i < hash.length; i++) {
			int v = hash[i];
			if (v < 0) v = 256 + v;
			if (v < 16) convertBud.append("0");
			convertBud.append(Integer.toString(v, 16).toUpperCase());
		}
		return convertBud.toString();
	}
}